// pages/navigation/navigation_walk/navigation_walk.js
import { server, mapKey } from "../../../utils/config.js";
//终点信息
let endPlace;
let timer;

Page({

    /**
     * 页面的初始数据
     */
    data: {
        server: server,
        markers: [], //标记
        distance: '--', //距离
        cost: '--', //预计时间
        polyline: [], //路线
        latitude: '34.529287', //中心纬度，用户视角，默认在畔池
        longitude: '109.108242', //中心经度，用户视角
        steps: [], //步骤路径
        isPopupShow: false, //底部弹窗显隐控制
        mapRotate: 0, //地图旋转角度
        topTipsText: "路径规划中，请稍候···", //顶部提示文本
    },

    /**
     * 打开其他导航
     */
    openOtherNav() {
        var endPlace = this.data.markers[1];
        wx.openLocation({
            longitude: Number(endPlace.longitude),
            latitude: Number(endPlace.latitude),
            name: endPlace.name,
            scale: 17
        });
    },

    /**
     * 关闭弹窗
     */
    closePopup() {
        this.setData({
            isPopupShow: false
        })
    },

    /**
     * 打开详情弹窗
     */
    goDetail() {
        this.setData({
            isPopupShow: true
        })
    },

    /**
     * 位置变化时，会调用
     */
    _locationChangeFn(res) {
        const placeData = [{
                longitude: res.longitude,
                latitude: res.latitude,
                name: "当前位置",
                iconPath: this.data.server + "/public/icon/start.png",
                id: 1,
            },
            {
                longitude: endPlace.longitude,
                latitude: endPlace.latitude,
                name: endPlace.name,
                iconPath: this.data.server + "/public/icon/end.png",
                id: 2,
            }
        ];
        //获取导航信息
        this.getNavInfo(placeData);
    },

    /**
     * 获取导航信息
     */
    getNavInfo(param) {
        var that = this;

        wx.request({
            url: "https://apis.map.qq.com/ws/direction/v1/walking/",
            data: {
                key: mapKey,
                from: param[0].latitude + "," + param[0].longitude,
                to: param[1].latitude + "," + param[1].longitude
            },
            method: "GET",
            header: {
                "content-type": "application/json"
            },
            success: function(c) {
                const resData = c.data;
                if (resData.status === 0 && resData.result.routes && resData.result.routes.length > 0) {
                    const route = resData.result.routes[0];
                    const polyline = route.polyline;
                    const points = [];
                    let currentLat = polyline[0];
                    let currentLon = polyline[1];
                    points.push({ latitude: currentLat, longitude: currentLon });
                    for (let i = 2; i < polyline.length; i += 2) {
                        if (i + 1 >= polyline.length) break; // 防止索引越界
                        const deltaLat = polyline[i] / 1000000;
                        const deltaLon = polyline[i + 1] / 1000000;
                        currentLat += deltaLat;
                        currentLon += deltaLon;
                        points.push({
                            latitude: currentLat,
                            longitude: currentLon,
                        });
                    }
                    const steps = route.steps;
                    //根据方向旋转地图
                    let orientationRotate = 0;
                    switch (steps[0].dir_desc) {
                        case "东北":
                            orientationRotate = 315;
                            break;
                        case "东":
                            orientationRotate = 270;
                            break;
                        case "东南":
                            orientationRotate = 225;
                            break;
                        case "南":
                            orientationRotate = 180;
                            break;
                        case "西南":
                            orientationRotate = 135;
                            break;
                        case "西":
                            orientationRotate = 90;
                            break;
                        case "西北":
                            orientationRotate = 45;
                            break;
                        default:
                            orientationRotate = 0;
                    }
                    //更新标记点和路径
                    that.setData({
                        distance: route.distance + "米",
                        cost: route.duration + "分钟",
                        latitude: param[0].latitude,
                        longitude: param[0].longitude,
                        markers: param,
                        polyline: [{
                            points: points,
                            color: "#4581c7", //路径颜色
                            width: 6
                        }],
                        mapRotate: orientationRotate,
                        topTipsText: steps[0].instruction,
                        steps: steps
                    });
                }
            },
            fail() {
                wx.showToast({
                    title: '定位异常！',
                    icon: 'none',
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        //获取传递过来的参数
        endPlace = {
            longitude: Number(options.e_longitude),
            latitude: Number(options.e_latitude),
            name: options.e_name,
        }
        const that = this;

        wx.getLocation({
            type: 'gcj02',
            success(res) {
                that._locationChangeFn(res);
            }
        })

        timer = setInterval(() => {
            wx.getLocation({
                type: 'gcj02',
                success(res) {
                    that._locationChangeFn(res);
                }
            })
        }, 5000)

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        //关闭监听实时位置变化
        clearInterval(timer);
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})